package cn.eonshine.cuba.inf.common.cert;

/**
 * ReadP12Cert.java
 * 版权所有(C) 2012 
 * 创建:cuiran 2012-07-31 15:50:53
 */
 
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.util.Enumeration;

import sun.misc.BASE64Encoder;
 
/**
 * TODO
 * @author cuiran
 * @version TODO
 */
public class ReadP12Cert {
 
	public static KeyStore getKeyStore(String file, String passwd) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
 
            KeyStore ks = KeyStore.getInstance("PKCS12");
 
            FileInputStream fis = new FileInputStream(file);
 
            // If the keystore password is empty(""), then we have to set
            // to null, otherwise it won't work!!!
            char[] nPassword = getPasswd(passwd);
 
            ks.load(fis, nPassword);
 
            fis.close();
            return ks;
	}
	
	private static char[] getPasswd(String passwd) {
		char[] nPassword = null;
		 if ((passwd == null) || passwd.trim().equals("")){
             nPassword = null;
         }else{
             nPassword = passwd.toCharArray();
         }
		 return nPassword;
	}
	
	private static String getKeyAlias(KeyStore ks) throws KeyStoreException {
		Enumeration enum1 = ks.aliases();
		 
        String keyAlias = null;

        if (enum1.hasMoreElements()) // we are readin just one certificate.
        {
            keyAlias = (String)enum1.nextElement();
            System.out.println("alias=[" + keyAlias + "]");
        }
        return keyAlias;
	}
	
	public static Certificate getCertificate(KeyStore ks) throws KeyStoreException {
		String keyAlias = getKeyAlias(ks);
		Certificate cert = ks.getCertificate(keyAlias);
		return cert;
	}
	
	public static PublicKey getPublicKey(KeyStore ks) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException {
		
        String keyAlias = getKeyAlias(ks);

        Certificate cert = ks.getCertificate(keyAlias);
        
        PublicKey pubkey = cert.getPublicKey();
        
        return pubkey;
	}
	
	public static PrivateKey getPrivateKey(KeyStore ks, String passwd) throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException {
		char[] nPassword = getPasswd(passwd);
        
        String keyAlias = getKeyAlias(ks);

        PrivateKey prikey = (PrivateKey) ks.getKey(keyAlias, nPassword);
        
        return prikey;
	}
	
	public static void main(String[] args) {
		
		final String KEYSTORE_FILE     = "C:/test/demoCA/certs/server.p12";
 
        final String KEYSTORE_PASSWORD = "123456";
 
        final String KEYSTORE_ALIAS    = "alias";
 
        try {
 
            KeyStore ks = getKeyStore(KEYSTORE_FILE, KEYSTORE_PASSWORD);
 
            System.out.println("keystore type=" + ks.getType());
 
            // Now we loop all the aliases, we need the alias to get keys.
            // It seems that this value is the "Friendly name" field in the
            // detals tab <-- Certificate window <-- view <-- Certificate
            // Button <-- Content tab <-- Internet Options <-- Tools menu
            // In MS IE 6.
 
//            Enumeration enum1 = ks.aliases();
// 
//            String keyAlias = null;
// 
//            if (enum1.hasMoreElements()) // we are readin just one certificate.
//            {
//                keyAlias = (String)enum1.nextElement();
//                System.out.println("alias=[" + keyAlias + "]");
//            }
 
            // Now once we know the alias, we could get the keys.
//            System.out.println("is key entry=" + ks.isKeyEntry(keyAlias));
            
            char[] nPassword = getPasswd(KEYSTORE_PASSWORD);
            
            String keyAlias = getKeyAlias(ks);
 
            PrivateKey prikey = (PrivateKey) ks.getKey(keyAlias, nPassword);
 
            Certificate cert = ks.getCertificate(keyAlias);
 
            PublicKey pubkey = cert.getPublicKey();
 
 
            System.out.println("cert class = " + cert.getClass().getName());
 
            System.out.println("cert = " + cert);
 
            System.out.println("public key = " + pubkey);
            System.out.println("===============PUBLIC KEY===================");
			BASE64Encoder base64Encoder=new BASE64Encoder();
			System.out.println(base64Encoder.encode(pubkey.getEncoded()));
			System.out.println("==================================");
            
            System.out.println("private key = " + prikey);
            System.out.println("=================PRIVATE KEY=================");
			System.out.println(base64Encoder.encode(prikey.getEncoded()));
			System.out.println("==================================");

            System.out.println(base64Encoder.encode(cert.getEncoded()));
            
            System.out.println("==================================");
            
        }
 
        catch (Exception e)
 
        {
 
            e.printStackTrace();
 
        }
 
 
	}
 
}

